<template>
  <div class="login">
    <el-button
      @click="dialogFormVisible = true"
      v-if="$store.state.uname === ''"
      type="primary"
      plain
      >登录</el-button
    >
    <el-dropdown v-else trigger="click" @command="handleCommend">
      <user-item></user-item>
    </el-dropdown>

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :append-to-body="atb"
      width="30%"
      @close="close('form')"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          :label-width="formLabelWidth"
          v-if="registFlag"
          prop="repassword"
        >
          <el-input v-model="form.repassword" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <div class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="confirm('form')">确 定</el-button>
        </div>
        <div>
          没有账号？点击<el-button
            type="text"
            style="color: lightblue; font-size: 18px"
            @click="regist"
            >注册</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UserItem from "./UserItem.vue";
import { login_success, login_fail } from "../../../plugins/notification";

export default {
  name: "Login",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      loginFlag: false, // vue-cookies hidden
      dialogFormVisible: false,
      atb: true, // dont change
      registFlag: false,
      title: "登录",
      form: {
        name: "",
        password: "",
        repassword: "",
      },
      formLabelWidth: "80px",
      rules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 1, message: "长度不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 4, message: "长度不能小于4个字符", trigger: "blur" },
        ],
        repassword: [
          { required: true, message: "再次输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    regist() {
      this.title = "注册";
      this.registFlag = true;
    },
    async login() {
      let name = this.form.name;
      let password = this.form.password;
      await this.$http
        .get("/auth/accredit", {
          params: {
            uname: name,
            password: password,
          },
        })
        .then(async () => {
          let res = await this.$http.get("/user/login", {
            params: {
              uname: name,
              password: password,
            },
          });
          // 登录成功 保存用户信息 vue store
          this.$store.state.uid = res.data.uid;
          this.$store.state.uname = res.data.uname;
          this.$store.state.avatar = res.data.avatar;
          this.$store.state.likedTalkIdList = res.data.likeTalkid;
          this.$router.replace("/refresh");
          login_success();
        })
        .catch((e) => {
          login_fail();
        });
    },
    async regist_confirm() {
      let res = await this.$http.post(
        "/user/register",
        {},
        {
          params: {
            uname: this.form.name,
            password: this.form.password,
          },
        }

      );
    },
    cancel() {
      this.dialogFormVisible = false;
    },
    confirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // login or regist!!!!!!!!!!!!!!!!!!!
          if (this.title == "注册") {
            // regist
            this.regist_confirm();
          } else {
            // login
            this.login();
          }
          this.dialogFormVisible = false;
        } else {
          alert("输入不合法，请确认!");
          return false;
        }
      });
      // this.dialogFormVisible = false;
    },
    close(formName) {
      this.$refs[formName].resetFields();
      this.registFlag = false;
      this.title = "登录";
      this.form.name = "";
      this.form.password = "";
      this.form.repassword = "";
    },
    handleCommend(command) {
      if (command == "signout") {
        this.$cookies.remove("fengyuan")
        this.$router.replace("/refresh"); // refresh curr route
        window.sessionStorage.clear();
        this.$store.commit("resetAll");
        console.log("登出");
      }
    },
  },
  created() {},
  components: {
    UserItem,
  },
  watch: {},
};
</script>

<style >
.login {
  margin-right: 70%;
  margin-top: 3%;
  margin-bottom: 1%;
}

.el-form {
  margin-left: 1%;
  /* margin-right: 1% !important; */
}

.el-dialog__body {
  padding-bottom: 0px !important;
}

.dialog-footer {
  padding-bottom: 10px;
}
</style>
